package com.lagou.edu.mvcframework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liuc
 * @date 2021/4/22
 * @description
 **/
public class DefaultAroundInterceptor implements AroundHandler{
    protected BeforeHandler beforeHandler;
    protected AfterHandler afterHandler;
    protected ExceptionHandler exceptionHandler;

    public DefaultAroundInterceptor(){

    }

    public void setAfterHandler(AfterHandler afterHandler) {
        this.afterHandler = afterHandler;
    }

    public void setBeforeHandler(BeforeHandler beforeHandler) {
        this.beforeHandler = beforeHandler;
    }

    public void setExceptionHandler(ExceptionHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
    }

    public DefaultAroundInterceptor(BeforeHandler beforeHandler, AfterHandler afterHandler, ExceptionHandler exceptionHandler){
        this.beforeHandler = beforeHandler;
        this.afterHandler = afterHandler;
        this.exceptionHandler = exceptionHandler;
    }

    @Override
    public void after(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            if(afterHandler != null){
                afterHandler.after(request,response);
            }
        }catch (Exception e){
            handleException(request,response,e);
        }
    }

    @Override
    public boolean before(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            if(beforeHandler != null){
                return beforeHandler.before(request,response);
            }
        }catch (Exception e){
            handleException(request,response,e);
        }
        return true;
    }

    @Override
    public void handleException(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
        if(exceptionHandler != null){
            exceptionHandler.handleException(request,response,e);
        }
    }
}
